// pages/studyWord/memorizeWord/memorizeWord.js

const app = getApp();
const httpUtils = require('../../../utils/httpUtils.js');


let wordlist = [{
  "id": "20061",
  "translate": "饥饿的",
  "word": "hungry"
}, {
  "id": "20072",
  "translate": "阿姨",
  "word": "aunt"
}, {
  "id": "20111",
  "translate": "鸡肉",
  "word": "chicken"
},
{
  "id": "20060",
  "translate": "纸张",
  "word": "paper"
}, {
  "id": "20073",
  "translate": "你好",
  "word": "hello"
}, {
  "id": "20211",
  "translate": "英语",
  "word": "english"
},
{
  "id": "20160",
  "translate": "盒子",
  "word": "box"
}, {
  "id": "20173",
  "translate": "今天",
  "word": "today"
}];

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: app.globalData.imageurl, //图片的总路径
    audiopath: app.globalData.voicepath,  //单词的声音路径
    innerAudioContext: new Object(),
    startX: 0, //开始坐标
    startY: 0,
    listData: wordlist, //传过来的所有单词数据
    groupList: [], //所有组的数据，传到模拟剪纸条也是所有组的数据都传过去
    wordlist: [], //当前页的单词列表
    studyWord: [], //已学习的单词 传到学后检测用
    currentPage: 1, //当前第几页
    totalPage: 1, //共几页
    studyGroup: 0, //学了（提交了）几组
    isOrder: true, //是否是顺序
    voicePosition: 0, //当前播放声音的下标
    packageid: '', //单词包id
    course_type: '',//0是体验词库 1正式词库
    flag: true, //显示隐藏提示剪纸条的弹窗的标志
    isCut: 1, //iscut 0不需要剪，为1先剪纸条
    groupNum: 1, //第几组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let totalPage = that.data.totalPage;
    //获取选词页传过来的单词, 并设置listData
    that.data.packageid = options.packageid;
    // let listData = that.data.listData;
    let listData = JSON.parse(options.studyData);
    let groupList = that.data.groupList;
    if (listData.length > 0) {
      let page = parseInt(listData.length / 5);
      let lastpageNum = listData.length % 5;
      if (lastpageNum > 0) {
        totalPage = page + 1;
      } else {
        totalPage = page;
      }
      console.log("totalPage=" + totalPage)
      for (let i = 0; i < listData.length; i++) {
        listData[i].click = 0;
        listData[i].clicktotalNum = 0;
        listData[i].fontw = 400;
        listData[i].isTouchMove = false
      }
      let currentPage = 1;
      let templist = new Array();
      for (var i = 0; i < listData.length; i++) {
        if (i < 5 * currentPage) {
          templist.push(listData[i]);
        } else {
          currentPage++;
          groupList.push(templist);
          templist = new Array();
          templist.push(listData[i]);
        }
      }

      if (groupList.length < totalPage) {
        groupList.push(templist);
      }
      that.setData({
        currentPage: 1,
        groupNum: 1,
        totalPage: totalPage,
        groupList: groupList,
      })
      console.log("groupList:" + JSON.stringify(groupList))
      //初始化当前页
      that.initPage();
    }

    //初始化audio
    that.data.innerAudioContext = wx.createInnerAudioContext();
    that.data.innerAudioContext.autoplay = false;
    that.data.innerAudioContext.loop = false;

  },

  //初始化当前页的数据
  initPage: function () {
    let that = this;
    //暂时用假数据
    //更新数据源，添加一些属性
    let groupList = that.data.groupList;
    let current = that.data.currentPage - 1;
    let temparr = new Array();
    temparr = temparr.concat(groupList[current]);
    for (let i = 0; i < temparr.length; i++) {
      temparr[i].click = 0;
      temparr[i].clicktotalNum = 0;
      temparr[i].fontw = 400;
      temparr[i].isTouchMove = false
    }

    that.setData({
      wordlist: temparr,
      voicePosition: 0,
      isOrder: true
    })
  },

  // 点击条目
  clickWord: function (e) {
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let word = e.currentTarget.dataset.word;
    let tmp = new Object;
    tmp = that.data.wordlist;

    // let audiosrc = that.data.audiopath + word + ".mp3";
    let audiosrc =e.currentTarget.dataset.voice;
    console.log("audiosrc:"+audiosrc);
    this.data.innerAudioContext.stop();
    this.data.innerAudioContext.src = audiosrc;
    this.data.innerAudioContext.play();

    for (var i = 0; i < tmp.length; i++) {
      if (i == idx) {
        console.log("点击了", idx)
        tmp[idx].clicktotalNum = parseInt(tmp[idx].clicktotalNum) + 1;;
        tmp[idx].fontw = 800;
        if (tmp[idx].click < 2) {
          tmp[idx].click = parseInt(tmp[idx].click) + 1;
        } else {
          tmp[idx].click = 1;
        }
        console.log("tmp[idx].click:", tmp[idx].click)
      } else {
        tmp[i].click = 0;
        tmp[i].fontw = 400;
      }
    }

    //更新数据
    that.setData({
      wordlist: tmp,
    })
    console.log("clickWord()方法中wordlist：" + JSON.stringify(that.data.wordlist))
  },

  /**
   * 上一页
   */
  lastPage: function () {
    let that = this;
    let wordlist = that.data.wordlist;
    let currentPage = that.data.currentPage;
    let studyGroup = that.data.studyGroup;
    for (var i = 0; i < wordlist.length; i++) {
      if (wordlist[i].clicktotalNum < 1) {
        wx.showToast({
          title: '当前页还有部分单词没进行识记不能进行查看上一页',
          icon: 'none'
        })
        return;
      }
    }
    if (currentPage > studyGroup) {
      this.submitWordList(3);//点击上一页没有剪纸条的提交 并且更新为上一页内容
    } else {
      if (currentPage - 1 > 0) {
        that.setData({
          groupNum: currentPage,
          currentPage: currentPage - 1,
        })
        that.initPage();
      }
    }

  },

  /**
   * 下一页--小剪刀--模拟剪纸条
   */
  nextPage: function () {
    let that = this;
    let wordlist = that.data.wordlist;
    let groupList = that.data.groupList;
    let currentPage = that.data.currentPage;
    let studyGroup = that.data.studyGroup;

    for (var i = 0; i < wordlist.length; i++) {
      if (wordlist[i].clicktotalNum < 1) {
        wx.showToast({
          title: '还有部分单词没进行识记不能进行下一步',
          icon: 'none'
        })
        return;
      }
    }
    //currentPage>studyGroup,还未提交，先提交该页
    if (currentPage > studyGroup) {
      this.submitWordList(2);
    } else {
      // 弹开始剪纸条弹窗, 
      // showCutTipDialog()
      that.setData({
        flag: false,
        isCut: 0
      })
      if (currentPage < groupList.length) {  //还有下一页
        that.setData({
          groupNum: currentPage,
          currentPage: currentPage + 1
        })
        that.initPage();
      } else if (currentPage == groupList.length) {
        that.setData({
          groupNum: groupList.length
        })
      }
    }
  },

  /**
   * 结束识记
   */
  finishStudy: function () {
    let that = this;
    let wordlist = that.data.wordlist;
    let studyWord = that.data.studyWord;
    let currentPage = that.data.currentPage;
    let groupList = that.data.groupList;
    console.log(JSON.stringify(wordlist))
    // for (var i = 0; i < wordlist.length; i++) {
    //   if (wordlist[i].clicktotalNum < 1) {
    //     wx.showToast({
    //       title: '当前页还有部分单词没进行识记不能进行提交',
    //       icon: 'none'
    //     })
    //     return;
    //   }
    // }
    studyWord = [];
    //只把学习的组数传到学后检测见面
    for (var i = 0; i < this.data.studyGroup; i++) {
      for (var j = 0; j < groupList[i].length; j++) {
        studyWord.push(groupList[i][j]);
      }
    }
    console.log("studyWord=" + JSON.stringify(studyWord))
    if (studyWord.length <= 0) {
      wx.showToast({
        title: '请先剪纸条，否则本页不计入学习。',
        icon: 'none'
      })
    } else {
      that.setData({
        studyWord: studyWord,
      })

      if (this.data.studyGroup == groupList.length) {
        //已学完  弹确认提交框
        // 是否结束识记单词
        that.showConfirmDialog("是否结束识记单词");
      } else {
        // 未学完  弹确认提交框
        // 还有部分单词没有识记完，是否结束识记
        that.showConfirmDialog("还未识记完,是否结束识记");
      }
    }

  },

  //弹确认提示框
  showConfirmDialog: function (message) {
    let that = this;
    let currentPage = that.data.currentPage;
    let studyGroup = that.data.studyGroup;
    let studyData = JSON.stringify(that.data.studyWord);
    wx.showModal({
      title: '温馨提示',
      content: message,
      success(res) {
        if (res.confirm) {
          //点击结束识记 判断当前页是否提交 如果没有提交 先调接口然后跳学后检测 
          // if (studyGroup < currentPage) {
          //   that.submitWordList(1);
          // } else {
          //   // 如果提交了直接跳学后检测
          //   wx.redirectTo({
          //     url: '/pages/studyWord/checkWord/checkWord?packageid=' + that.data.packageid + '&studyData=' + studyData,
          //   })
          // }
          // 如果提交了直接跳学后检测
          wx.redirectTo({
            url: '/pages/studyWord/checkWord/checkWord?packageid=' + that.data.packageid + '&studyData=' + studyData,
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })


  },
  /**
   * 提交，调结束识记的接口
   * isClose 1,结束2，剪纸条3上一页
   */
  submitWordList: function (isClose) {
    let that = this;
    let currentPage = that.data.currentPage;
    let wordlist = that.data.wordlist;
    let studyGroup = that.data.studyGroup;
    let studyData = JSON.stringify(that.data.studyWord);
    wx.showLoading({
      title: '',
      mask: true
    })
    let temA = '';
    for (var i = 0; i < wordlist.length; i++) {
      if (temA == '') {
        temA = wordlist[i].id;
      } else {
        temA = temA + "," + wordlist[i].id
      }
    }
    console.log("temA=" + temA)
    httpUtils.stopStudy({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      word_list: temA,
      package_id: that.data.packageid,
    }).then((res) => {
      if (isClose == 1) {
        //跳转学后检测
        console.log("跳转学后检测")
        wx.redirectTo({
          url: '/pages/studyWord/checkWord/checkWord?packageid=' + that.data.packageid + '&studyData=' + studyData,
        })
      } else if (isClose == 2 || isClose == 3) {
        studyGroup = studyGroup + 1;
        // 弹开始剪纸条弹窗, 
        // showCutTipDialog()
        that.setData({
          flag: false,
          isCut: 1,
          studyGroup: studyGroup,
        })
        if (isClose == 2) {
          if (currentPage < that.data.groupList.length) {  //还有下一页
            that.setData({
              groupNum: currentPage,
              currentPage: currentPage + 1,
            })
            that.initPage();
          } else if (currentPage == that.data.groupList.length) {
            that.setData({
              groupNum: that.data.groupList.length,
            })
          }
        } else {
          if (currentPage - 1 > 0) {
            that.setData({
              groupNum: currentPage,
              currentPage: currentPage - 1
            })
            that.initPage();
          }
        }
      }
    });
  },

  //点击弹窗按钮开始剪纸条
  gopaper: function () {
    let that = this;
    that.setData({
      flag: true
    })
    let currentPage = that.data.groupNum;
    let studyGroup = that.data.studyGroup;
    let isCut = that.data.isCut;
    let groupdata = JSON.stringify(that.data.groupList);
    console.log("gopaper()-currentPage:" + currentPage)
    wx.navigateTo({
      url: '/pages/studyWord/paperCut/paperCut?groupdata=' + groupdata + '&currentPage=' + currentPage + '&studyGroup=' + studyGroup + '&isCut=' + isCut,
    })
  },

  /**
  * 小喇叭--点击顺序播放
  */
  orderPlay: function () {
    let that = this;
    let tmp = that.data.wordlist;
    let voicePosition = that.data.voicePosition;
    let isOrder = that.data.isOrder;
    for (var i = 0; i < tmp.length; i++) {
      if (i == voicePosition) {
        console.log("点击了voicePosition", voicePosition)
        tmp[voicePosition].clicktotalNum = parseInt(tmp[voicePosition].clicktotalNum) + 1;;
        tmp[voicePosition].fontw = 600;
        if (tmp[voicePosition].click < 2) {
          tmp[voicePosition].click = parseInt(tmp[voicePosition].click) + 1;
        } else {
          tmp[voicePosition].click = 1;
        }
      } else {
        tmp[i].click = 0;
        tmp[i].fontw = 400;
      }
    }
    //播放读音
    let audiosrc = that.data.audiopath + tmp[voicePosition].word + ".mp3";
    this.data.innerAudioContext.stop();
    this.data.innerAudioContext.src = audiosrc;
    this.data.innerAudioContext.play();
    //改变voicepositon
    if (isOrder) {
      if (voicePosition + 1 < tmp.length) {
        voicePosition = voicePosition + 1;
      }
    } else {
      if (voicePosition - 1 >= 0) {
        voicePosition = voicePosition - 1;
      }
    }
    if (voicePosition == tmp.length - 1 || voicePosition == 0) {
      isOrder = !isOrder;
    }
    that.setData({
      voicePosition: voicePosition,
      isOrder: isOrder,
      wordlist: tmp
    })

  },

  //加入难词
  addHardWord: function (e) {
    let that = this;
    let id = e.currentTarget.dataset.id; //记录id
    //请求加入生词本的接口 
    wx.showLoading({
      title: '',
      mask: true
    })
    httpUtils.addhardWord({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      id: id,
    }).then((res) => {
      wx.showToast({
        title: '加入难词本成功',
      })
    });

  },

  //查看详解
  gotodetail: function (e) {
    let word = e.currentTarget.dataset.word; //单词
    // let url = "http://dict.youdao.com/search?q=" + word + "&keyfrom=new-fanyi.smartResult";
    // let url ="https://fanyi.baidu.com/#en/zh/"+word;
    // let url = "https://translate.google.cn/#view=home&op=translate&sl=en&tl=zh-CN&text=" + word;
    // wx.navigateTo({
    //   url: '/pages/web/web?url=' + url,
    // })

    wx.navigateTo({
      url: '/pages/studyWord/wordDetail/wordDetail?word=' + word,
    })
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时，重置所有操作项
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let temlist = that.data.wordlist;
    console.log("idx:", idx);
    console.log(e)
    temlist.forEach(function (v, i) {
      if (v.isTouchMove) { //只操作为true的
        v.isTouchMove = false;
      }
    })

    that.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      wordlist: temlist
    })
  },

  //滑动事件处理
  touchmove: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index; //当前索引
    let temlist = that.data.wordlist;
    let startX = that.data.startX;
    let startY = that.data.startY;
    let touchMoveX = e.changedTouches[0].clientX;//滑动变化坐标
    let touchMoveY = e.changedTouches[0].clientY;//滑动变化坐标
    let angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });//获取角度
    temlist.forEach(function (v, i) {
      v.isTouchMove = false;
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) {  //右滑
          v.isTouchMove = false;
        } else {                    //左滑
          v.isTouchMove = true;
        }
      }
    })

    //更新数据
    that.setData({
      wordlist: temlist
    })
  },

  /**  
  * 计算滑动角度 
  * @param {Object} start 起点坐标
  * @param {Object} end 终点坐标
  */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值 
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

})